package com.biz.primus.ms.commodity.service.backend;

import com.biz.primus.commodity.vo.backend.SyncEvaluationDataVo;
import com.biz.primus.common.utils.JsonUtil;
import com.biz.primus.ms.base.service.AbstractBaseService;
import com.biz.primus.ms.base.service.DataSyncService;
import com.biz.primus.ms.commodity.dao.po.TemporaryEvaluation;
import com.biz.primus.ms.commodity.dao.redis.EvaluationRedisDao;
import com.biz.primus.ms.commodity.dao.repository.evaluation.EvaluationRepository;
import com.biz.primus.ms.commodity.dao.repository.evaluation.TemporaryEvaluationRepository;
import com.biz.primus.ms.commodity.dao.repository.product.ProductRepository;
import com.biz.primus.ms.commodity.feign.VendorFeignClient;
import com.biz.primus.ms.commodity.trans.Evaluation2EvaluationRo;
import com.biz.primus.ms.commodity.trans.SyncEvaluationDataVo2TemporaryEvaluation;
import com.google.common.base.Preconditions;
import com.google.common.base.Stopwatch;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.net.URL;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangcheng
 * @date 2017/3/24
 * @reviewer
 * @see
 */
@Slf4j
@Service
public class ImportEvaluationDataService extends AbstractBaseService {

    @Autowired
    private TemporaryEvaluationRepository temporaryEvaluationRepository;

    @Autowired
    private EvaluationRepository evaluationRepository;

    @Autowired
    private EvaluationRedisDao evaluationRedisDao;

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private VendorFeignClient vendorRepository;

    private static final int PIPELINE_COUNT = 500;

    @Transactional
    public void importTemporaryEvaluation() {
        Stopwatch stopwatch = Stopwatch.createStarted();
        List<SyncEvaluationDataVo> syncEvaluationDataVos;
        URL resourceUrl = ImportEvaluationDataService.class.getClassLoader().getResource("importfile/evaluation_origin_utf.txt");
        Preconditions.checkArgument(resourceUrl != null);
        String path = resourceUrl.getPath();
        log.debug("文件路径为：{}", path);
        StringBuilder builder = new StringBuilder();
        try (InputStream in = new FileInputStream(path);
             Reader reader = new InputStreamReader(in, "UTF-8");
             BufferedReader bufferedReader = new BufferedReader(reader)
        ) {
            String str;
            while (StringUtils.isNotBlank(str = bufferedReader.readLine())) {
                builder.append(str);
            }
            syncEvaluationDataVos = JsonUtil.json2Obj(builder.toString(),List.class,SyncEvaluationDataVo.class);

            List<SyncEvaluationDataVo> vos = Lists.newArrayList();
            for (SyncEvaluationDataVo vo : syncEvaluationDataVos) {
                vos.add(vo);
                if (vos.size() == PIPELINE_COUNT) {
                    this.handleData(vos);
                    vos.clear();
                }
            }
            this.handleData(vos);
            log.debug("读取的评价数量为：{}", syncEvaluationDataVos.size());
        } catch (IOException e) {
            log.debug("读取组合商品数据出错", e);
        }
        log.debug("耗时：{}", stopwatch.elapsed(TimeUnit.MILLISECONDS));
    }


    public void syncEvaluationToRedis() {
        log.info("开始同步评价信息到Redis.");
        DataSyncService.DataSyncHelper.syncData(evaluationRepository, evaluationRedisDao, new Evaluation2EvaluationRo());
        log.info("同步评价信息到Redis完成.");
    }

    private void handleData(List<SyncEvaluationDataVo> vos) {
        List<TemporaryEvaluation> temporaryEvaluations = Lists.newArrayList();
        for (SyncEvaluationDataVo vo : vos) {
            TemporaryEvaluation temporaryEvaluation = new SyncEvaluationDataVo2TemporaryEvaluation().apply(vo);
            Preconditions.checkArgument(temporaryEvaluation != null);
            temporaryEvaluation.setId(idService.getNextId());
            temporaryEvaluations.add(temporaryEvaluation);
        }
        temporaryEvaluationRepository.save(temporaryEvaluations);
        log.debug("保存评价完成，数量为：{}", temporaryEvaluations.size());
    }
}
